<?php
class product extends CP_Controller {

    function __construct() {
        parent::__construct('product','product_','id');
    }
	function convertCurrency($num=0){
		echo get_currency("USD","VND",$num);
	}
    function index(){
        echo $c=$this->load->view('cms/cp/05_product/viewport',$this->assigns,true);
    }
	
	function tokeninput($Id=0){
        $q=$this->input->get_post('q');
        $data = $this->db
                ->select('product_id as id,product_title as title')
                ->like('product_title',$q)
				->where('product_id <>',$Id)
                ->from($this->table)
                ->order_by('product_insert', 'DESC')
                ->limit(10)
                ->get()
				->result();
        $R=$data;
        $this->output->set_header('Content-type: application/json');
        $this->output->set_output(json_encode($R));
    }
	
    function cate_binding($type='CLOTHING'){
		$this->load->model('cp/category_model');
        $data = $this->category_model->binding($type);
		if(isset($data['rows']))
            $data['rows']=$this->category_model->buildTreeArray($data['rows']);
		if(isset($data['aaData']))
            $data['aaData']=$this->category_model->buildTreeArray($data['aaData']);
        if(isset($data['rows']))
            return $data['rows'];
		if(isset($data['aaData']))
            return $data['aaData'];
        return null;
    }
    function editpanel($type="CLOTHING"){
		$this->assigns->type=$type;
		$this->assigns->cates = $this->cate_binding($type);
        $Id=(int)$this->input->post('Id');
        if($Id>0){
            $this->assigns->item=$this->backend_model->onGet($Id);
			if(!empty($this->assigns->item)){
                $relatedids=  explode (',', $this->assigns->item->product_related);
                $R["related"]=$this->db
						->select('product_id as id,product_title as title')
						->where_in('product_id',$relatedids)
						->from($this->table)
						->order_by('product_insert', 'DESC')
						->get()
						->result();
			}
		}
        $c=$this->load->view('cms/cp/05_product/editpanel',$this->assigns,true);
        $R["result"] = 1;
        $R["message"]='SUCCESS !';
        $R["htmlreponse"]=$c;
        $this->output->set_header('Content-type: application/json');
        $this->output->set_output(json_encode($R));
    }
	function binding_by_type($type="CLOTHING"){
		$this->backend_model->datatables_config=array(
				"table"=>"product",
				"select"=>"SELECT SQL_CALC_FOUND_ROWS 
					product.product_id,
					product.product_title,
					product.product_title_vi,
					product.product_alias,
					product.product_code,
					product.product_sizes,
					product.product_colors,
					product.product_price,
					product.product_price_vi,
					product.product_status,
					product.product_position,
					product.product_category_id,
					product.product_total_amount,
					product.product_amount,
					product.product_thumb,
					product.product_tag,
					product.product_insert,
					product.product_update,
					product.product_type
					",
				"from"=>"FROM product",
				"where"     =>"WHERE product_type = '$type'",
				"order_by"=>"ORDER BY `product_insert` DESC",
				"columnmaps"=>array(
						
				)
		);
		$this->bindingdata();
	}
	
	function get_size_by_type($type='CLOTHING'){
		//$size_model = new Backend_Model('size','size_','id');
		$query = $this->db
                ->from('size')
				->where('size_category_type',"$type")
                ->order_by('size_position', 'ASC')
				->order_by('size_insert', 'DESC')
                ->get();
        $result = $query->result();
		$this->output->set_header('Content-type: application/json');
        $this->output->set_output(json_encode($result));
    }
	
	function get_color_by_type($type='CLOTHING'){
		//$size_model = new Backend_Model('size','size_','id');
		$query = $this->db
                ->from('color')
				->where('color_category_type',"$type")
                ->order_by('color_position', 'ASC')
				->order_by('color_insert', 'DESC')
                ->get();
        $result = $query->result();
		$this->output->set_header('Content-type: application/json');
        $this->output->set_output(json_encode($result));
    }
	function ondeletedata(){
		$this->beforedelete();
        $R["result"] = -1;
        $R["message"] = ("This function to requires an administrative account.<br/>Please check your authority, and try again.");
        if ($this->privilege()) {
            $id = (int) $this->input->post('Id');
            if ($id > 0) {
                $tmp = $this->backend_model->onGet($id);
                if ($tmp) {
                    if (
                            (!empty($tmp->{$this->prefix . "lock"})) &&
                            $tmp->{$this->prefix . "lock"} == 'locked'
                    ) {
                        $R["message"] = ("Can't delete 'System' record. Record have been locked.");
                    } else {
						$this->backend_model->db->trans_begin();
						$rs = $this->backend_model->onDelete($id);
						if ($this->backend_model->db->_error_number() != 0) $R["error_messages"][] = $this->backend_model->db->_error_message();
						if ($this->backend_model->db->trans_status() === FALSE){
							$this->backend_model->db->trans_rollback();
							$R["result"] = -901;
							$R["message"] = ("[ROLLBACK]System rejected your data.<br/>Please check data input and try again.<br/>");
							$R["message"].= implode('<br />',$R["error_messages"]);
							
						}else{
							$this->backend_model->db->trans_commit();
							if ($rs === true) {
								$R["result"] = 1;
								$R["message"] = ("Success. Data have been save.");
							} else {
								$R["result"] = -1;
								$R["last_query"] = $this->backend_model->db->last_query();
								$R["message"] = ("System rejected your data.<br/>Please check data input and try again.<br/>");
								$R["message"].= implode('<br />',$R["error_messages"]);
							}
						}
                    }
					//$R["message"] = ($tmp->{$this->prefix . "lock"});
                }else {
                    $R["message"] = ("Record does't exist.");
                }
            } else {
                $R["message"] = ("Id invalid.");
            }
        }
        $this->output->set_header('Content-type: application/json');
        $this->output->set_output(json_encode($R));
	}
	function oncommitdata(){
		$this->beforecommit();
		$R["result"] = -1;
        $R["message"] = ascii_to_entities("This function to requires an administrative account.<br/>Please check your authority, and try again.");
        if ($this->privilege()) {
            $Params = $this->input->get_post('Params');
			if(!empty($Params)){
				if(isset($Params['product_content']))$Params['product_content'] = $_REQUEST['Params']['product_content'];
				if(isset($Params['product_content_vi']))$Params['product_content_vi'] = $_REQUEST['Params']['product_content_vi'];
				$Id = (int) $this->input->post('Id');
				$relateds = explode(',',$Params['product_related']);
				$this->backend_model->db->trans_begin();
				if ($Id != 0) {
					$record=$this->backend_model->onGet($Id);
					if($record){
						$rs = $this->backend_model->onUpdate($Id, $Params);
						if ($this->backend_model->db->_error_number() != 0) $R["error_messages"][] = $this->backend_model->db->_error_message();
						if ($rs === true){
							$relateds_old = explode(',',$record->product_related);
							$relateds_add  = array_diff($relateds, $relateds_old);
							$relateds_remove  = array_diff($relateds_old, $relateds);
							if(!empty($relateds_add)){
								$this->backend_model->db
									->set('product_related', "CONCAT(product_related,if(product_related='','',','),'$record->product_id')", FALSE)
									->where_in('product_id', $relateds_add)
									->not_like('product_related', $record->product_id)
									->update('product');
								if ($this->backend_model->db->_error_number() != 0) $R["error_messages"][] = $this->backend_model->db->_error_message();
							}
							
							if(!empty($relateds_remove)){
								$this->backend_model->db
									->set('product_related', "
										if(
											product_related = '$record->product_id',
											'', 
											if(
												product_related like '$record->product_id,',
												REPLACE(product_related,'$record->product_id,',''),
												if(
													product_related like '%,$record->product_id%',
													REPLACE(product_related,',$record->product_id',''),
													product_related
												)
											)
										)", FALSE)
									->where_in('product_id', $relateds_remove)
									->like('product_related', $record->product_id)
									->update('product');
								if ($this->backend_model->db->_error_number() != 0) $R["error_messages"][] = $this->backend_model->db->_error_message();
							}
							
						}
					}else{
						$R["result"] = -203;
						$R["message"] = "Record doesn't exist.";
						echo (json_encode($R));
						return;
					}
				} else {
					$rs = $this->backend_model->onInsert($Params);
					if ($this->backend_model->db->_error_number() != 0) $R["error_messages"][] = $this->backend_model->db->_error_message();
					if ($rs === true){
						$R['last_id'] = $this->backend_model->_get_last_insert_id();
						if(!empty($Params['product_category_id'])){
							$this->backend_model->db
								->set('Total', 'Total + 1', FALSE)
								->where('Id', $Params['product_category_id'])
								->update('categories');
							if ($this->backend_model->db->_error_number() != 0) $R["error_messages"][] = $this->backend_model->db->_error_message();
						}
						
					}
				}
				if ($this->backend_model->db->trans_status() === FALSE){
					$this->backend_model->db->trans_rollback();
					$R["result"] = -901;
					$R["message"] = ("[ROLLBACK]System rejected your data.<br/>Please check data input and try again.");
					$R["message"].= implode('<br />',$R["error_messages"]);
				}else{
					$this->backend_model->db->trans_commit();
					if ($rs === true) {
						$R["result"] = 1;
						$R["message"] = ("Success. Data have been save.");
					} else {
						$R["result"] = -1;
						$R["last_query"] = $this->backend_model->db->last_query();
						$R["message"] = ("System rejected your data.<br/>Please check data input and try again.<br/>");
						$R["message"].= implode('<br />',$R["error_messages"]);
					}
				}
			}else $R["message"] = "Data invalid.";
        }
        echo (json_encode($R));
	}
	function initproduct(){
		return;
		for($i=1;$i<=42;$i++){
			$Params = array(
				'product_category_id'=>4,
				'product_code'=>"BV1109$i",
				'product_price'=>10,
				'product_price_vi'=>212900,
				'product_title'=>"Bánh vẽ BV1109$i",
				'product_title_vi'=>"Bánh vẽ BVK1109$i",
				'product_alias'=>"banh-ve-bv1109$i",
				'product_thumb'=>"/data/image/banh-ve/bv$i.png",
				'product_type'=>"cake",
				'product_tag'=>"banh, bánh, bánh sinh nhật, banh sinh nhat,bánh cưới, banh cuoi,bánh cupkes, bánh vẽ",
				'product_desc'=>"Thông Tin: 20cm - 250.000 vnđ
25cm - 300.000 vnđ
30cm - 380.000 vnđ
Giao Hàng tận nơi (giá trên chưa bao gồm phí vận chuyển)
Nhận làm theo mẫu.",
			);
			$rs = $this->backend_model->onInsert($Params);
			echo $this->backend_model->db->_error_message();
		}
	}
}

?>